/****************************************************************************************
 Copyright © 2003-2012 ZTEsoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.goods.IGoodsPriceFactorService;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.GoodsPriceFactorUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProdFeeCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.util.ContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <Description> <br>
 *
 * @author tengg<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2021年3月15日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.service.attr.handler <br>
 */

public class FeeStandardMonthlyRentAttrHandler extends AbstractAttrHandler<KiteInst, AttrData> {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    IInfServiceBus infServiceBus;

    @Autowired
    private IGoodsPriceFactorService goodsPriceFactorService;

    @Override
    public void def(KiteAttr attr, KiteInst inst, AttrData data) {
        String sceneInstId = data.getSceneInstId();

        String custId = data.getCustId();
        String offerId = inst.getSpecId();
        Offer offerSpec = ProdFeeCache.get(offerId);
        if (Objects.isNull(offerSpec)) {
            offerSpec = OfferCache.get(offerId);
        }
        Map<String, Object> offerMap = offerSpec.getOfferMap();
        String discntCode = KiteMapUtils.getString(offerMap, "discntCode");
        Map feeProdPrice = new HashMap();
        List<KiteOfferInst> offerInstList;
        if (CuccPosServiceUtils.isBatchAccept(sceneInstId)) {
            offerInstList = Collections.singletonList(GoodsPriceFactorUtil.getBatchMainInstId(sceneInstId));
        }
        else {
            offerInstList = querySceneInstService.listMainOfferInsts(sceneInstId);
        }

        boolean isNeedCalc = this.isNeedToCalc(data);
        if (isNeedCalc) {
            offerInstList.forEach(offerInst -> {
                // 实时调接口查询价格
                Map<String, Object> goodsPrice = goodsPriceFactorService.getFeeProdPrice(sceneInstId, custId, offerInst.getOfferId(), (KiteOfferInst) inst);
                if (Objects.nonNull(goodsPrice)) {
                    feeProdPrice.putAll(goodsPrice);
                }
            });
        }
        if (KiteMapUtils.isNotEmpty(feeProdPrice)) {
            List<Map> feeItemPrices = (List<Map>) feeProdPrice.get("feeItemPrice");
            for (Map map : feeItemPrices) {
                String price = KiteMapUtils.getString(map, "price");
                String feeCode = KiteMapUtils.getString(map, "feeCode");
                if (StringUtils.isNotEmpty(price) && KiteStringUtils.isEqual(feeCode, discntCode)) {
                    attr.setOriginValue(price);
                    attr.setDefaultValue("");
                    attr.setValue(price);
                    attr.setValueDesc(price);
                    inst.setAttr(attr);
                }
            }
        }
        //在这写联动处理
        String prodInstId = "";
        KiteProdInst kiteProdInst = null;
        if(KiteListUtils.isNotEmpty(offerInstList)){
            prodInstId = offerInstList.get(0).getInstId();
        }
        List<KiteProdInst> prodInstsFromMain = querySceneInstService.listProdInstsFromOfferInst(custId, prodInstId);
        if (KiteListUtils.isNotEmpty(prodInstsFromMain)) {
            kiteProdInst = prodInstsFromMain.get(0);
        }
        //从prodInst里面获取attrMap的属性
        if(null!=kiteProdInst && KiteStringUtils.equals(kiteProdInst.getSpecId(),"1003538") && KiteMapUtils.isNotEmpty(kiteProdInst.getAttrMap())){//政务云信创产品
            Map<String, KiteAttr> kiteAttrMap = kiteProdInst.getAttrMap();
            if(KiteStringUtils.equals(inst.getSpecId(),"60040635")){//云主机使用费
                //云主机类型
                KiteAttr yzjlxAttr = kiteAttrMap.get("200000111");
                //云主机规格
                KiteAttr yzjggAttr = kiteAttrMap.get("200003395");
                String attrValue = getAttrValue("60040635",yzjlxAttr.getValue(),yzjggAttr.getValue());
                attr.setValue(attrValue);
                attr.setDefaultValue(attrValue);
            }else if(KiteStringUtils.equals(inst.getSpecId(),"60040637")){//系统盘使用费
                //系统盘类型
                KiteAttr xtplxAttr = kiteAttrMap.get("200001866");
                //系统盘规格
                KiteAttr xtpggAttr = kiteAttrMap.get("200004148");
                String attrValue = getAttrValue("60040637",xtplxAttr.getValue(),xtpggAttr.getValue());
                attr.setValue(attrValue);
                attr.setDefaultValue(attrValue);
            }else if (KiteStringUtils.equals(inst.getSpecId(),"60040638")){//数据盘使用费
                //数据盘类型
                KiteAttr sjplxAttr = kiteAttrMap.get("200004149");
                //数据盘规格
                KiteAttr sjpggAttr = kiteAttrMap.get("200003386");
                String attrValue = getAttrValue("60040638",sjplxAttr.getValue(),sjpggAttr.getValue());
                attr.setValue(attrValue);
                attr.setDefaultValue(attrValue);
            }else if (KiteStringUtils.equals(inst.getSpecId(),"60040639")){//存储盘使用费
                //存储服务类型
                KiteAttr ccfwlxAttr = kiteAttrMap.get("200004150");
                //存储大小
                KiteAttr ccdxAttr = kiteAttrMap.get("200004151");
                String attrValue = getAttrValue("60040639",ccfwlxAttr.getValue(),ccdxAttr.getValue());
                attr.setValue(attrValue);
                attr.setDefaultValue(attrValue);
            }else if(KiteStringUtils.equals(inst.getSpecId(),"60040640")){//机柜使用费
                //机柜（U)
                KiteAttr jgAttr = kiteAttrMap.get("200004152");
                List<DcPublic> dcPublicList = DcPublicCache.getByPcode("202110181536","offer_bbyz","60040640");
                List<DcPublic> dcPublicNeed = dcPublicList.stream().filter(dcPublic -> KiteStringUtils.equals(dcPublic.getCodea(),jgAttr.getValue())).collect(Collectors.toList());
                if(KiteListUtils.isNotEmpty(dcPublicNeed)){
                    attr.setValue(dcPublicNeed.get(0).getCodec());
                    attr.setDefaultValue(dcPublicNeed.get(0).getCodec());
                }
            }
        }
        //天津附加商品对应资费的标准月租赋值
        String offerIds = DcPublicCache.getCodea("20220315","TJFJSPZF");
        if (KiteStringUtils.isNotEmpty(offerIds) && KiteStringUtils.equalsAny(offerId,offerIds.split(SymbolConsts.COMMA))) {
            //获取对应资费的订购个数
            List<KiteProdInst> kiteProdInstList1 = querySceneInstService.listProdInstsFromOfferInst(data.getCustId(), inst.getInstId());
            Map<String, KiteAttr> attrMap = kiteProdInstList1.get(0).getAttrMap();
            KiteAttr gsAttr = attrMap.get(LocalKeyConsts.ATTR_200003299);
            //获取资费单价
            Map<String, KiteAttr> attrMap1 = inst.getAttrMap();
            KiteAttr djAttr = attrMap1.get(LocalKeyConsts.UNIT_PRICE);
            //计算标准月租
            if (KiteStringUtils.isNotEmpty(djAttr.getValue()) && KiteStringUtils.isNotEmpty(gsAttr.getValue())) {
                BigDecimal djValueBd = new BigDecimal(djAttr.getValue());
                BigDecimal gsValueBd = new BigDecimal(gsAttr.getValue());
                BigDecimal attrValueBd = djValueBd.multiply(gsValueBd);
                String attrValueString = attrValueBd.setScale(0,BigDecimal.ROUND_HALF_DOWN).toString();
                attr.setValue(attrValueString);
                attr.setDefaultValue(attrValueString);
            }
        }

        super.def(attr, inst, data);
    }

    private String getAttrValue(String pcode,String pcodea,String pcodob){
        String attrValue = null;
        List<DcPublic> dcPublicList = DcPublicCache.getByPcode("202110181536","offer_bbyz",pcode);
        List<DcPublic> dcPublicNeed = dcPublicList.stream().filter(dcPublic -> KiteStringUtils.equals(dcPublic.getCodea(),pcodea)&&KiteStringUtils.equals(dcPublic.getCodeb(),pcodob)).collect(Collectors.toList());
        if(KiteListUtils.isNotEmpty(dcPublicNeed)){
            attrValue=dcPublicNeed.get(0).getCodec();
        }
        return attrValue;
    }

    /**
     * 变更，重提初始化，模版还原不需要进行算价
     * @param data
     * @return
     */
    private boolean isNeedToCalc(AttrData data) {
        boolean result = true; // 默认进行算价
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        // 模板还原不进行询价
        if ("sceneTempl".equals(data.getExtAttributes().get("entry")) || (KiteMapUtils.isNotEmpty(extParams) && extParams.containsKey("nodeCode"))) {
            result = false;
        }
        //变更业务的场景初始化过程不进行询价
        if (KiteStringUtils.equalsAny(data.getServiceOfferId(), ServiceOfferConsts.SERVICE_OFFER_MODIFY, LocalServiceOfferConsts.SERVICE_OFFER_FEE_MODIFY)
            && !KeyConsts.IFTRUE_T.equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE))
            && !"workOrder".equals(querySceneInstService.getExtParameterValue(data.getSceneInstId(), "initSource"))) {
            result = false;
        }
        return result;
    }
}
